package org.abc.fund.repository.factorRepository;

import org.abc.fund.entity.factorEntity.DerivedFactor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 衍生因子Repository
 */
@Repository
public interface DerivedFactorRepository extends JpaRepository<DerivedFactor, Long> {

    /**
     * 根据因子代码查找衍生因子
     */
    Optional<DerivedFactor> findByFactorCode(String factorCode);
    
    /**
     * 根据因子代码查找衍生因子（包含组件）
     */
    @Query("SELECT df FROM DerivedFactor df LEFT JOIN FETCH df.components WHERE df.factorCode = :factorCode")
    Optional<DerivedFactor> findByFactorCodeWithComponents(@Param("factorCode") String factorCode);
    /**
     * 根据是否启用查找衍生因子列表
     */
    List<DerivedFactor> findByEnabled(Boolean enabled);

    /**
     * 统计启用的衍生因子数量
     */
    long countByEnabledTrue();

    /**
     * 根据因子名称模糊查询
     */
    @Query("SELECT df FROM DerivedFactor df WHERE df.factorName LIKE %:factorName%")
    List<DerivedFactor> findByFactorNameContaining(@Param("factorName") String factorName);

    /**
     * 根据因子代码模糊查询
     */
    @Query("SELECT df FROM DerivedFactor df WHERE df.factorCode LIKE %:factorCode%")
    List<DerivedFactor> findByFactorCodeContaining(@Param("factorCode") String factorCode);

    /**
     * 分页查询衍生因子
     */
    Page<DerivedFactor> findByEnabled(Boolean enabled, Pageable pageable);

    /**
     * 检查因子代码是否存在
     */
    boolean existsByFactorCode(String factorCode);

    /**
     * 根据创建人查找衍生因子列表
     */
    List<DerivedFactor> findByCreatedBy(String createdBy);

    void deleteByFactorCode(String factorCode);

    /**
     * 多条件搜索衍生因子
     */
    @Query("SELECT df FROM DerivedFactor df WHERE " +
           "(:name IS NULL OR df.factorName LIKE %:name%) AND " +
           "(:code IS NULL OR df.factorCode LIKE %:code%) AND " +
           "(:operator IS NULL OR df.operator LIKE %:operator%) AND " +
           "(:enabled IS NULL OR df.enabled = :enabled)")
    Page<DerivedFactor> searchDerivedFactors(@Param("name") String name,
                                            @Param("code") String code,
                                            @Param("operator") String operator,
                                            @Param("enabled") Boolean enabled,
                                            Pageable pageable);
}